package com.kssoft.ebd.spider.processor;

import cn.hutool.core.thread.ThreadUtil;
import com.kssoft.ebd.spider.common.CommonUtils;
import com.kssoft.ebd.spider.common.NullCookiesException;
import com.kssoft.ebd.spider.common.PageModelType;
import com.kssoft.ebd.spider.common.config.SpiderConfig;
import com.kssoft.ebd.spider.http.HttpClientUtil;
import com.kssoft.ebd.spider.pool.WebDriverPool;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.*;
import java.util.Map;
import java.util.Set;

/**
 * @author liwu
 * @since 2025/6/18
 */
@Component
public class HomeProcessor implements PageProcessor {

    private Set<Cookie> cookies;
    private static final Site SITE = Site.me().setRetryTimes(3).setSleepTime(100).setTimeOut(3000);

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SpiderConfig spiderConfig;
    @Autowired
    private WebDriverPool webDriverPool;

    @Override
    public void process(Page page) {

        // 判断登录状态 ，是否含有 login 文字
        if (page.getHtml().xpath("//*[@id=\"password\"]").match() || page.getRawText().contains("登录")) {
            login();
            logger.info("login执行成功");
        }
        logger.info("登录成功");
    }

    @Override
    public Site getSite() {

        try {
            // 从内存或文件加载Cookie
            CommonUtils.getCookieToSite(SITE, PageModelType.Home, SpiderConfig.HOME_COOKIE_FILE_PATH);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException | NullCookiesException e) {
           // cookie不存在
            login();
            // 从内存或文件加载Cookie
            try {
                CommonUtils.getCookieToSite(SITE, PageModelType.Home, SpiderConfig.HOME_COOKIE_FILE_PATH);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            } catch (ClassNotFoundException | NullCookiesException ex) {
                throw new RuntimeException(ex);
            }
        }
        return SITE;
    }

    //使用 selenium 来模拟用户的登录获取cookie信息  跳转到主页
    private WebDriver login(){
        WebDriver driver  = CommonUtils.webDriverHashMap.get(PageModelType.Home);
        if (driver == null) {
            driver = webDriverPool.getSigle();
            CommonUtils.webDriverHashMap.put(PageModelType.Home, driver);
        }
        driver.get(spiderConfig.getHomePageUrl());
        WebElement username = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("username")));
        WebElement password = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("password")));

        username.clear();
        username.sendKeys(spiderConfig.getUsername());

        password.clear();
        password.sendKeys(spiderConfig.getPassword() + Keys.ENTER);
        ThreadUtil.sleep(3000);
//        driver.findElement(By.xpath("/html/body/div[2]/form/div/input[8]")).click();
//
//        ThreadUtil.sleep(5000);

        //跳转到 http://smartexpress/home.mvc?ticket=ST-649-CzP1r39ZkQTOpCfHEMJF-      登录成功返回的location 链接  访问后是主页
        cookies = driver.manage().getCookies();
        try {
            // 保存Cookie到内存和文件
            CommonUtils.saveHomeCookies(cookies);
            //打印 cookies
            for (Cookie cookie : cookies) {
                logger.error(cookie.getName() + ":" + cookie.getValue());
            }
        } catch (IOException e) {

        }
        return driver;
    }
    /**
     * 获取驱动
     */
    public WebDriver getHomeDriver() {
        WebDriver webDriver = CommonUtils.webDriverHashMap.get(PageModelType.Home);
        if(webDriver == null){
            login();
        }
        return webDriver;
    }

    /**
     * 启动爬虫
     * @return
     */
    public WebDriver start() {
        Map<String, String> homeCookies = null;
        try {
            homeCookies = CommonUtils.getHomeCookies();
        } catch (Exception e) {

            logger.error("获取主页cookie 失败");
        }
        if (homeCookies != null) {
//            Spider.create(this).addUrl(spiderConfig.getHomePageUrl()).run();
            // 判断登录状态 ，是否含有效
            if(isLogin()){
                return getHomeDriver();
            }
        }
        // 重新登录
        login();
        return CommonUtils.webDriverHashMap.get(PageModelType.Home);
    }

    /**
     * 获取主页cookies
     * @return
     */
    public Map<String, String> getHomeCookies() {
        if(isLogin()){
            try {
                return CommonUtils.getHomeCookies();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (NullCookiesException e) {
                throw new RuntimeException(e);
            }
        }
        start();
        Map<String, String> homeCookies = null;
        try {
            homeCookies = CommonUtils.getHomeCookies();
        } catch (Exception e) {
            logger.error("获取主页cookie 失败");
        }
        return homeCookies;
    }
    /**
     * 获取主页cookies，判断登录状态
     */
    public boolean isLogin() {
        Map<String, String> homeCookies = null;
        try {
            homeCookies = CommonUtils.getHomeCookies();
        } catch (Exception e) {
            System.out.println("获取主页cookie 失败");
        }
        if(homeCookies != null){
            try {
                String result = HttpClientUtil.doGet(spiderConfig.getHomePageUrl(), null, homeCookies, null);
                if(result.contains("登录") || result.contains("password")){
                    logger.error("主页登录状态: false");
                    CommonUtils.removeCookies(PageModelType.Home);
                    return false;
                }
                logger.info("主页登录状态: true");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取主页cookie 登录状态异常");
                throw new RuntimeException(e);
            }
        }
        logger.error("主页登录状态: false");
        return false;
    }
}
